package com.itheima.reggie.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.mapper.DishFlavorMapper;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class DishServiceImpl implements DishService {

    @Autowired
    DishMapper dishMapper;

    @Autowired
    DishFlavorMapper dishFlavorMapper;

    @Override
    public void insert(DishDto dishDto) {

        dishMapper.insert(dishDto);
        String id = dishDto.getId();
        System.err.println("=======" + id + "=======");

        //需要拿到插入dish时自动生成的id,再遍历List<DishFlavor> flavors数组,给每个DishFlavor设置dish_id,并插入到dish_flavor表中

        List<DishFlavor> flavors = dishDto.getFlavors();
        if (flavors != null) {
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(id);
                dishFlavorMapper.insert(flavor);
            }
        }

    }

    @Override
    public PageInfo<DishDto> selectByPage(int page, int pageSize, String name) {
        //开启分页,通过某种方式改变了SQL语句,后面加了limit  起始索引, 查询记录数
        PageHelper.startPage(/*当前第几页*/page,/*每页多少条*/pageSize);
        //查询所有,只返回指定页
        List<DishDto> list = dishMapper.selectAllByName(name);

        for (DishDto dishDto : list) {
            System.err.print(dishDto.getName() + "========");
            System.err.println(dishDto.getCategoryName());
        }


        //封装PageInfo
        PageInfo<DishDto> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public void delete(String id) {
        dishMapper.delete(id);
    }

    @Override
    public void updateStatus(String id, int is0or1) {//0表示是要切换到停用,1表示要切换到启用
        if (is0or1 == 0) {
            dishMapper.updateStatus(id, 0);
        } else {
            dishMapper.updateStatus(id, 1);
        }
    }

    @Override
    public DishDto selectAllById(String id) {
        DishDto dishDto = dishMapper.selectAllById(id);//这个dishDto中缺少List<DishFlavor> flavors,需要根据dishId查询dish_flavor表

        List<DishFlavor> flavors = dishFlavorMapper.selectByDishId(dishDto.getId());

        dishDto.setFlavors(flavors);

        return dishDto;
    }

    @Override
    public void updateById(DishDto dishDto) {
        //修改dish表中name category_id price image description update_time update_user属性
        dishMapper.updateById(dishDto);
    }

    @Override
    public List<Dish> selectByCategoryId(String categoryId) {
        return dishMapper.selectByCategoryId(categoryId);
    }
}
